<!--
value             ====>   双向数据绑定，已经上传的文件列表（受控）
multiple          ====>   是否支持多选文件，ie10+ 支持。开启后按住 ctrl 可选择多个文件。
apiObj            ====>   远程数据API对象
params            ====>   远程数据默认请求参数
name              ====>   发到后台的文件参数名，默认是file
accept            ====>   接受上传的文件类型, 详见 input accept Attribute(https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/file#accept)
maxSize           ====>   最大允许接受的文件大小
-->
<template>
  <div class="s-upload">
    <a-upload-dragger
        v-model:fileList="trueFileList"
        :accept="accept"
        :name="name"
        :multiple="multiple"
        :action="action"
        :beforeUpload="beforeUpload"
        @change="handleChange"
        @remove="handleRemove"
    >
        <p class="ant-upload-drag-icon base-mb5">
          <CloudUploadOutlined />
        </p>
        <p class="upload-text">点击上传，或将附件拖拽到此处</p>
    </a-upload-dragger>
  </div>
</template>

<script setup>
import { onMounted, ref, watch } from 'vue'
import { message, notification } from 'ant-design-vue'
import config from "@/config/upload"
const emit = defineEmits(['update:value', 'change'])
const props = defineProps({
  value: {
    type: Array,
    default: []
  },
  multiple: {
    type: Boolean,
    default : true
  },
  apiObj: {
    type: Object,
    default: () => {}
  },
  params: {
    type: Object,
    default: () => {}
  },
  name: {
    type: String,
    default: 'file'
  },
  accept: {
    type: String,
    default: () => {
      return 'image/gif, image/jpeg, image/png'
    }
  },
  maxSize: {
    type: Number,
    default: config.maxSizeFile
  },
})

watch(() => props.value, (curr, old) => {
  trueFileList.value = curr
})

const action = ref('')
const trueFileList = ref([])
onMounted(() => {
  trueFileList.value = props.value
})

const beforeUpload = (file, fileList) => {
  const acceptIncludes = props.accept.replace(/\s/g,"").split(",").includes(file.type)
  if(!acceptIncludes){
    notification.warning({
      message: `上传文件警告`,
      description: '选择的文件为不被允许的类型，仅允许：' + props.accept
    })
    return false
  }

  const maxSize = file.size / 1024 / 1024 < props.maxSize;
  if (!maxSize) {
    message.error(`上传文件大小不能超过 ${props.maxSize}MB!`)
    return false
  }

  return true
}

const handleChange = (info) => {
  // console.log('handleChange', info)
  // emit('update:value', '')
  emit('change', info)
}
const handleRemove = (info) => {
  // emit('update:value', info)
  // emit('change', )
}
// const action =
</script>

<style scoped>
.upload-text {
  color: #999;
}
</style>
